package com.fulu.game.bi.controller.channel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.fulu.game.bi.common.controller.BaseController;
import com.fulu.game.bi.common.exception.BizException;
import com.fulu.game.bi.entity.po.auth.BiUser;
import com.fulu.game.bi.entity.po.channel.RegistSource;
import com.fulu.game.bi.entity.vo.Result;
import com.fulu.game.bi.entity.vo.channel.source.RegisterSourceDisplayVO;
import com.fulu.game.bi.entity.vo.channel.source.RegisterSourceQueryVO;
import com.fulu.game.bi.entity.vo.channel.source.RegisterSourceSaveVO;
import com.fulu.game.bi.redis.service.auth.BiUserService;
import com.fulu.game.bi.redis.service.channel.RegisterSourceService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 渠道管理
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/register-source")
public class RegisterSourceController extends BaseController {

    @Autowired
    private RegisterSourceService registerSourceService;

    @Autowired
    private BiUserService biUserService;

    /**
     * 保存渠道
     */
    @PostMapping("/save")
    public Result<RegistSource> save(RegisterSourceSaveVO vo) {
        RegistSource res = registerSourceService.save(vo);

        return Result.success().data(res).msg("保存成功");
    }

    /**
     * 查询渠道列表
     */
    @PostMapping("/list")
    public Result<Page<RegisterSourceDisplayVO>> list(RegisterSourceQueryVO vo) {
        PageInfo<RegisterSourceDisplayVO> page = registerSourceService.list(vo);

        return Result.success().data(page).msg("查询成功");
    }

    // 下载导入模板(空模板)
    @PostMapping(value = "/export")
    public void exportEmpty(HttpServletResponse response) {
        String title = "导入渠道模板";
        try {
            ExportParams exportParams = new ExportParams(title, "sheet1", ExcelType.XSSF);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, RegisterSourceDisplayVO.class, new ArrayList<>());
            Sheet sheet1 = workbook.getSheet("sheet1");
            CellStyle textStyle = workbook.createCellStyle();
            DataFormat format = workbook.createDataFormat();
            textStyle.setDataFormat(format.getFormat("@"));
            sheet1.setDefaultColumnStyle(2, textStyle);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title, "UTF-8"));
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            log.error("下载导入模板失败:{}", e, e);
        }
    }

    /**
     * 上传excel文件
     */
    @PostMapping(value = "/upload")
    public Result upload(@RequestParam("file") MultipartFile upload) {
        final ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        List<RegisterSourceDisplayVO> registerSources = new ArrayList<>();
        try {
            registerSources = ExcelImportUtil.importExcel(upload.getInputStream(), RegisterSourceDisplayVO.class, importParams);
        } catch (Exception e) {
            log.error("批量新增渠道异常:{}", e, e);
            return Result.error().msg("excel解析出错");
        }
        if (CollectionUtils.isEmpty(registerSources)) {
            throw new BizException("导入数据为空");
        }
        // 检查不重复platform and name
        Map<Integer, Integer> platformMap = new HashMap<>();
        Map<Integer, Set<Integer>> groupIdsMap = new HashMap<>();

        for (int i = 0; i < registerSources.size(); i++) {
            RegisterSourceDisplayVO item = registerSources.get(i);
            int rowNo = i + 3;
            if (Objects.isNull(item.getPlatform()) || StringUtils.isBlank(item.getName())) {
                throw new BizException("第" + rowNo + "行,渠道号和渠道名称不能为空");
            }
            if (Objects.nonNull(platformMap.get(item.getPlatform().toString()))) {
                throw new BizException("第" + platformMap.get(item.getPlatform().toString()) + "行和第" + rowNo + "行,渠道号重复");
            }
            if (Objects.nonNull(platformMap.get(item.getName()))) {
                throw new BizException("第" + platformMap.get(item.getName()) + "行和第" + rowNo + "行,渠道名称重复");
            }
            platformMap.put(item.getPlatform(), rowNo);
            Set<Integer> groupIdSet = new HashSet<>();
            if (StringUtils.isNotBlank(item.getGroupIds())) {
                item.setGroupIds(item.getGroupIds().replaceAll("，", ","));
                String[] split = item.getGroupIds().split(",");
                groupIdSet = Arrays.stream(split).mapToInt(Integer::parseInt).boxed().collect(Collectors.toSet());
            }
            groupIdsMap.put(item.getPlatform(), groupIdSet);

        }
        List<Integer> platformList = platformMap.keySet().stream().map(item -> Integer.valueOf(item)).collect(Collectors.toList());
        Integer[] tempArr = new Integer[platformList.size()];
        tempArr = platformList.toArray(tempArr);
        List<RegistSource> platSources = registerSourceService.findByPlatforms(tempArr);
        if (CollectionUtils.isNotEmpty(platSources)) {
            StringBuilder sb = new StringBuilder("");
            for (RegistSource platSource : platSources) {
                sb.append("第" + platformMap.get(platSource.getPlatform().toString()) + "行,渠道号已存在\n");
            }
            throw new BizException(sb.toString());
        }
        Date now = new Date();
        BiUser currentUser = biUserService.getCurrentUser();
        List<RegistSource> sources = new ArrayList<>(registerSources.size());
        for (RegisterSourceDisplayVO vo : registerSources) {
            RegistSource registSource = new RegistSource();
            registSource.setPlatform(vo.getPlatform());
            registSource.setName(vo.getName());
            registSource.setWechatMerchantId(4);
            registSource.setAlipayMerchantId(1);
            registSource.setCreateTime(now);
            registSource.setUpdateTime(now);
            registSource.setAdminId(currentUser.getId());
            sources.add(registSource);
        }
        int batch = registerSourceService.createBatch(sources);
        log.info("新增渠道:{}", batch);

        List<RegistSource> regSources = registerSourceService.findByPlatforms(platformMap.keySet().toArray(new Integer[0]));
        int rels = registerSourceService.createBatchRel(regSources, groupIdsMap);
        log.info("新增渠道关系:{}", rels);

        return Result.success().data(null).msg("保存成功");
    }


}
